#region License
//-----------------------------------------------------------------------------
// Copyright (c) 2008, Aaron MacDougall, Daniel Jeffery
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
//   this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of Aaron MacDougall or Daniel Jeffery nor the names of its contributors may
//   be used to endorse or promote products derived from this software without
//   specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion

namespace Agro2D
{
    /// <summary>
    /// This class represents all graphical and/or interactive objects in a
    /// game. It can be used on it's own for animations and collision events,
    /// or can be derrived from for a more flexible approach.
    /// 
    /// Most defining characteristics of a Sprite object are contained in a
    /// SpriteProperties member. This allows IAnimation objects to modify the
    /// sprite without keeping a reference to the actual Sprite.
    /// </summary>
    public class Sprite : ICloneable
    {
        #region Fields
        private SpriteManager spriteManager;
        private string type;
        private string name;
        private uint layerNum;
        private uint deleteLayerNum;
        private uint newLayerNum = 0;
        private bool drawable;
        private bool deleted;
        private bool cull = true;
        private bool locked = false;
        private SpriteProperties spriteProperties;
        private CollisionProperties collisionProperties;
        private IAnimation animation;
        private Vector2[] positions = new Vector2[4];
        TextureReference verticeTexRef;
        #endregion

        #region Events
        /// <summary>
        /// Triggered when a collision between two Sprite objects has occurred.
        /// </summary>
        /// <returns>true if there was a response, otherwise false.</returns>
        public delegate bool CollisionHandlerDelegate(Sprite sprite1, Sprite sprite2);
        public CollisionHandlerDelegate CollisionHandler;
        #endregion

        #region Properties
        /// <summary>
        /// Gets the SpriteManager object in posession of the Sprite.
        /// </summary>
        public SpriteManager SpriteManager
        {
            get { return this.spriteManager; }
            set { this.spriteManager = value; }
        }

        [ImportAttribute]
        public bool Cull
        {
            get { return this.cull; }
            set
            {
                this.cull = value;
            }
        }

        /// <summary>
        /// Locked in editor?
        /// </summary>
        [ImportAttribute]
        public bool Locked
        {
            get { return this.locked; }
            set
            {
                this.locked = value;
            }
        }
        /// <summary>
        /// Get/Set the type name of the Sprite.
        /// </summary>
        [ImportAttribute] 
        public string Type
        {
            get { return this.type; }
            set
            {
                Debug.Assert(value.Length > 0);
                this.type = value;
            }
        }

        /// <summary>
        /// Get/Set the name of the Sprite.
        /// </summary>
        [ImportAttribute] 
        public string Name
        {
            get { return this.name; }
            set
            {
                Debug.Assert(value.Length > 0);
                this.name = value;
            }
        }

        /// <summary>
        /// Get/Set the layer number that the sprite resides on.
        /// </summary>
        [ImportAttribute] 
        public uint LayerNum
        {
            get { return this.layerNum; }
            set
            {
                Debug.Assert(value >= 0 && value < 8, "Layer number given is higher than the number of layers or less than 0");
                this.layerNum = value;
            }
        }

        /// <summary>
        /// Get/Set the layer number that the sprite will be deleted from if the Deleted property is set.
        /// </summary>
        public uint DeleteLayerNum
        {
            get { return this.deleteLayerNum; }
            set
            {
                Debug.Assert(value >= 0 && value < 8, "Layer number given is higher than the number of layers or less than 0");
                this.deleteLayerNum = value;
            }
        }

        public uint NewLayerNum
        {
            get { return this.newLayerNum; }
            set
            {
                this.newLayerNum = value;
            }
        }
        

        /// <summary>
        /// Is this sprite drawable?
        /// </summary>
        [ImportAttribute]
        public bool Drawable
        {
            get { return this.drawable; }
            set
            {
                this.drawable = value;
            }
        }

        /// <summary>
        /// Get/Set the properties of the Sprite.
        /// </summary>
        public SpriteProperties SpriteProperties
        {
            get { return this.spriteProperties; }
            set
            {
                Debug.Assert(value != null);
                this.spriteProperties = value;
            }
        }

        /// <summary>
        /// Get/Set the collision properties of the Sprite.
        /// </summary>
        public CollisionProperties CollisionProperties
        {
            get { return this.collisionProperties; }
            set
            {
                Debug.Assert(value != null);
                this.collisionProperties = value;
            }
        }

        /// <summary>
        /// Get/Set the animation performed on the Sprite.
        /// </summary>
        public IAnimation Animation
        {
            get { return this.animation; }
            set { this.animation = value; }
        }

        /// <summary>
        /// Marks this sprite for deletion.
        /// </summary>
        public bool Deleted
        {
            get { return this.deleted; }
            set
            {
                this.deleted = value;
            }
        }

        /// <summary>
        /// Holds reference to a vertice texture ref for the edto
        /// </summary>
        public TextureReference VerticeTexRef
        {
            get { return this.verticeTexRef; }
            set
            {
                this.verticeTexRef = value;
            }
        }

        
        #endregion

        #region Constructors/Destructors
        public Sprite()
        {
            this.type = "none";
            this.spriteProperties = new SpriteProperties();
            this.collisionProperties = new CollisionProperties();
            this.animation = null;
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="spriteManager">
        /// SpriteManager object in posession of this Sprite.
        /// </param>
        public Sprite(SpriteManager spriteManager)
        {
            Debug.Assert(spriteManager != null);

            this.spriteManager = spriteManager;
            this.type = "none";
            this.spriteProperties = new SpriteProperties();
            this.collisionProperties = new CollisionProperties();
            this.animation = null;
        }

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="spriteManager">
        /// SpriteManager object in posession of this Sprite.
        /// </param>
        /// <param name="type">The type name of the Sprite.</param>
        /// <param name="spriteProperties">Properties of the Sprite.</param>
        /// <param name="collisionProperties">
        /// Collision properties of the sprite.
        /// </param>
        /// <param name="animation">
        /// Sprite animation. May be set to null for no animation.
        /// </param>
        public Sprite(
            SpriteManager spriteManager,
            string type,
            SpriteProperties spriteProperties,
            CollisionProperties collisionProperties,
            IAnimation animation
            )
        {
            Debug.Assert(spriteManager != null);

            this.spriteManager = spriteManager;
            Type = type;
            SpriteProperties = spriteProperties;
            CollisionProperties = collisionProperties;
            this.animation = animation;
        }
        #endregion

        /// <summary>
        /// The assigned animation is updated. Override to perform your game
        /// logic. Remember to call base.Update() so that the animation gets
        /// updated.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public virtual void Update(GameTime gameTime)
        {
            if (this.animation != null)
                this.animation.Animate(gameTime, spriteProperties);
        }

        /// <summary>
        /// Draws the Sprite.
        /// </summary>
        /// <param name="spriteBatch">SpriteBatch to draw with.</param>
        public virtual void Draw(SpriteBatch spriteBatch, ref Rectangle viewport, float scale)
        {
            if(this.spriteProperties.IsVisible &&
                this.spriteProperties.Texture != null
                )
            {
                // Used to force drawing at the top left of an image, instead of
                // the middle. Also allows rotation around the centre.
                Vector2 center = new Vector2();
                center.X = this.spriteProperties.SourceRectangle.Width / 2;
                center.Y = this.spriteProperties.SourceRectangle.Height / 2;

                // Snap to pixel positions, to prevent blurry sprites
                int xPixelPos = (int)(this.spriteProperties.Position.X + 0.5f);
                int yPixelPos = (int)(this.spriteProperties.Position.Y + 0.5f);
                xPixelPos += viewport.X;
                yPixelPos += viewport.Y;

                spriteBatch.Draw(
                    TextureManager.Instance.GetTexture(this.spriteProperties.Texture),
                    new Vector2(xPixelPos, yPixelPos) + center,
                    this.spriteProperties.SourceRectangle,
                    this.spriteProperties.Tint,
                    this.spriteProperties.Rotation,
                    center,
                    this.spriteProperties.Scale,
                    this.spriteProperties.SpriteEffect,
                    0
                );

                
                // scaling camera
                //xPixelPos += viewport.X;
                //yPixelPos += viewport.Y;                
               // spriteBatch.Draw(
               //    TextureManager.Instance.GetTexture(this.spriteProperties.Texture),
               //    new Vector2(xPixelPos * scale, yPixelPos * scale) + center,
               //    this.spriteProperties.SourceRectangle,
               //    this.spriteProperties.Tint,
               //    this.spriteProperties.Rotation,
               //    center,
               //    this.spriteProperties.Scale * scale,
               //    this.spriteProperties.SpriteEffect,
               //    0
               //);
                 
            }

            // TO DO: Only works if editor is in debug
#if DEBUG
            DrawBoundingBox(spriteBatch, ref viewport);
#endif
        }

        /// <summary>
        /// If in editor
        /// </summary>
        void DrawBoundingBox(SpriteBatch spriteBatch, ref Rectangle viewport)
        {
            if(this.SpriteManager.InLevelEditor && this.spriteManager.ShowDebugVertices 
                && verticeTexRef != null)
            {
                if(this.CollisionProperties.CollisionType == CollisionType.BoundingBox)
                {
                    Rectangle rect = this.CollisionProperties.BoundingBox;

                    rect.X += (int)this.SpriteProperties.Position.X + viewport.X;
                    rect.Y += (int)this.SpriteProperties.Position.Y + viewport.Y;

                    positions[0].X = rect.Left;
                    positions[0].Y = rect.Top;

                    positions[1].X = rect.Right;
                    positions[1].Y = rect.Top;

                    positions[2].X = rect.Right;
                    positions[2].Y = rect.Bottom;

                    positions[3].X = rect.Left;
                    positions[3].Y = rect.Bottom;

                    Texture2D texture = TextureManager.Instance.GetTexture(verticeTexRef);

                    Rectangle destRect = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, 4);

                    spriteBatch.Draw(texture,
                        destRect, new Color(255,255,255,150));

                    destRect = new Rectangle(rect.Left, rect.Top, 4, rect.Bottom - rect.Top);

                    spriteBatch.Draw(texture,
                        destRect, new Color(255, 255, 255, 150));


                    destRect = new Rectangle(rect.Left, rect.Bottom, (rect.Right - rect.Left) + 4, 4);

                    spriteBatch.Draw(texture,
                        destRect, new Color(255, 255, 255, 150));

                    destRect = new Rectangle(rect.Right, rect.Top, 4, rect.Bottom - rect.Top);

                    spriteBatch.Draw(texture,
                        destRect, new Color(255, 255, 255, 150));
                }
            }
        }

        public virtual void MoveToLayer(uint toLayer)
        {
            if(toLayer == this.LayerNum) return;
            this.Deleted = true;
            this.DeleteLayerNum = this.LayerNum;
            this.NewLayerNum = toLayer;
        }

        /// <summary>
        /// Called when a collision occurs with another Sprite object.
        /// </summary>
        /// <param name="otherSprite">The Sprite object collided with.</param>
        /// <returns>true if there was a response, otherwise false.</returns>
        public virtual bool OnCollision(Sprite otherSprite)
        {
            return false;
        }

        #region IClonable Implementation
        /// <summary>
        /// Returns a cloned version of this object. Important: You must override this in inherited classes!
        /// Set clonedObject.Drawable = this.Drawable and clonedObject.LayerNum = this.LayerNum;
        /// </summary>
        /// <returns>Cloned version of this object.</returns>
        public virtual object Clone()
        {
            IAnimation animation = null;

            if(this.animation != null)
                animation = (IAnimation)this.animation.Clone();

            Sprite clonedObject = new Sprite(
                this.spriteManager,
                this.type,
                (SpriteProperties)this.spriteProperties.Clone(),
                (CollisionProperties)this.collisionProperties.Clone(),
                animation
                );

            clonedObject.Drawable = this.Drawable;
            clonedObject.LayerNum = this.LayerNum;

            return clonedObject;
        }
        #endregion
    }
}